package com.yj.web.controllers.admin;

import com.yj.passport.entity.UserPassport;
import com.yj.passport.service.PassportService;
import com.yj.web.model.BaseWebResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by yesiming on 2017/8/1
 */
public class BaseController {

    private static final Log logger = LogFactory.getLog(BaseController.class);

    @Autowired
    private PassportService passportService;

    public  Long getHostId(HttpServletRequest request) {
        String pubTicket = request.getHeader("t");
        if (!StringUtils.isEmpty(pubTicket)) {
            long hostId = 0;
            UserPassport passport = null;
            passport = passportService.getPassportByTicket4Web(pubTicket);
            if (passport != null) {
                hostId = passport.getUserId();
                if (logger.isDebugEnabled()) {
                    logger.debug("-------hostId " + hostId);
                }
                return hostId;
            }
        }
        return 0L;
    }

    public boolean doError(BaseWebResult baseWebResult, BindingResult... bindingResult) {
        for (BindingResult result : bindingResult) {
            result.getAllErrors();

            if (result.hasErrors()) {
                StringBuffer message = new StringBuffer("");
                List<ObjectError> errors = result.getAllErrors();
                for (ObjectError objectError : errors) {
                    message.append(objectError.getDefaultMessage());
                    message.append(" | ");
                }
                baseWebResult.setCd(1);
                baseWebResult.setMsg(message.toString());
                return true;
            }
        }

        return false;
    }
}
